#include "SDLEngine.h"
#include "SDLInput.h"

SDLEngine* SDLEngine::instance = 0;

SDLEngine::SDLEngine()
	:quit(false)
{

}

SDLEngine::~SDLEngine()
{
}

void SDLEngine::Start()
{
	Initialise();
}

void SDLEngine::Start(const int screenWidth, const int screenHeight)
{
	Initialise(screenWidth, screenHeight);
}

void SDLEngine::Start(const int screenWidth, const int screenHeight, const bool debugMode)
{
	Initialise(screenWidth, screenHeight, debugMode);
}

void SDLEngine::Start(const bool debugMode)
{
	Initialise(SCREEN_WIDTH, SCREEN_HEIGHT, debugMode);
}

void SDLEngine::Run()
{
	while(!SDLInput::GetInstance()->HasQuit())
	{
		SDLInput::GetInstance()->Poll();

		Update();
		Draw();
	}
}

void SDLEngine::Update()
{
	std::vector<SDLComponent*>::iterator iter;
	for(iter = SDLComponent::allComponents.begin(); iter != SDLComponent::allComponents.end(); iter++)
	{
		(*iter)->Update();
	}
}

void SDLEngine::Draw()
{
	SDL_FillRect(screen, 0, SDL_MapRGB(screen->format,0,0,0));

	std::vector<SDLComponent*>::iterator iter;
	for(iter = SDLComponent::allComponents.begin(); iter != SDLComponent::allComponents.end(); iter++)
	{
		(*iter)->Draw();
	}

	if(SDL_Flip(screen) == -1)
	{
		return;
	}
}

void SDLEngine::Initialise(const int width, const int height, const bool debugMode)
{
	//standard input/ output/ error file pointers
	FILE *fpStdIn, *fpStdOut, *fpStdErr;

	if(debugMode)
	{
		_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

		if(AllocConsole())
		{
			//Assign the stdin/ stdout/ stderr streams to the newly created console
			_tfreopen_s(&fpStdIn, _T("CONIN$"), _T("r"), stdin);
			_tfreopen_s(&fpStdOut, _T("CONOUT$"), _T("w"), stdout);
			_tfreopen_s(&fpStdErr, _T("CONOUT$"), _T("w"), stderr);
		}
	}

	if(SDL_Init( SDL_INIT_EVERYTHING ) == -1)
	{
		return;
	}

	screen = SDL_SetVideoMode( width
							 , height
							 , SCREEN_BPP
							 , SDL_SWSURFACE);

	if(screen == 0)
	{
		return;
	}

	SDL_WM_SetCaption("SDL Base", 0);
}
